#include "widget.h"
#include "ui_widget.h"
#include "QDebug"
#include "QFileDialog"
#include "QStandardItemModel"
#include "QUrl"
#include "QSoundEffect"
#include "QModelIndex"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    effect = new QSoundEffect(this);

    QSound
}

Widget::~Widget()
{
    delete ui;
}

void Widget::play(int index)
{
    effect->setSource(playList[index]);
    //    effect->setLoopCount(QSoundEffect::Infinite);
    //    effect->setVolume(1.0);
    effect->play();
}
void Widget::on_pushButton_clicked()
{
    auto path = QFileDialog::getExistingDirectory(this, "请选择音乐所在目录");
    //根据音乐目录获取内部所有的mp3, wav文件
    qInfo() << path;
    QDir dir(path);
    auto musicList = dir.entryList(QStringList()<<"*.wav");

    QStringList* list = new QStringList();
    for (auto file : musicList) {
        playList.append(QUrl::fromLocalFile(path + "/" + file));

        list->append(file);
    }

    qInfo() << playList;

    ui->listView->addItems(*list);
    QModelIndex* index = new QModelIndex;
    ui->listView->setCurrentIndex(*index);
}

void Widget::on_pushButton_3_clicked()
{
    if (effect->status() == QSoundEffect::Null) {
        qInfo() << "null";
        auto index = ui->listView->currentIndex().row();
        if (index < 0) {
            index = 0;
        }

        qInfo() << playList[index];
        play(index);
        return;
    }

    if (effect->isPlaying()) {
        qInfo() << "is playing";

        effect->stop();
    } else {
        qInfo() << "not playing";
        auto index = ui->listView->currentIndex().row();
        if (index < 0) {
            index = 0;
        }

        qInfo() << playList[index];
        play(index);
    }
}

void Widget::on_pushButton_4_clicked()
{
    int idx = ui->listView->currentIndex().row() - 1;
    if (idx < 0) {
        return;
    }

    ui->listView->setCurrentIndex(ui->listView->model()->index(idx, 0));

    play(idx);
    qInfo() << ui->listView->currentIndex().row();
}

void Widget::on_pushButton_6_clicked()
{
    int idx = ui->listView->currentIndex().row() + 1;
    if (idx >= playList.length()) {
        return;
    }

    ui->listView->setCurrentIndex(ui->listView->model()->index(idx, 0));

    play(idx);
    qInfo() << ui->listView->currentIndex().row();
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    play(index.row());
}
